"""
文件名: import_mysql_to_neo4j.py
功能: 自动从 MySQL 导入软件故障数据到 Neo4j 图数据库
"""

import mysql.connector
from py2neo import Graph, Node, Relationship
from tqdm import tqdm
from StructureGraph_Construction import MYSQL_CONFIG,NEO4J_CONFIG


print("🔌 正在连接 MySQL 与 Neo4j ...")

try:
    mysql_conn = mysql.connector.connect(**MYSQL_CONFIG)
    cursor = mysql_conn.cursor(dictionary=True)
    graph = Graph(NEO4J_CONFIG["uri"], auth=(NEO4J_CONFIG["user"], NEO4J_CONFIG["password"]))
    print("✅ 数据库连接成功！\n")
except Exception as e:
    print("❌ 数据库连接失败：", e)
    exit()

# ================================
# 3️⃣ 导入 FaultType 节点
# ================================

cursor.execute("SELECT * FROM fault_type")
rows = cursor.fetchall()

for row in tqdm(rows, desc="导入 FaultType"):
    node = Node("FaultType",
                type_id=row["type_id"],
                name=row["name"],
                description=row["type_declaration"])
    graph.merge(node, "FaultType", "type_id")

print(f"✅ FaultType 导入完成，共 {len(rows)} 条记录。\n")

# ================================
# 4️⃣ 导入 FaultInfo 节点 + 关系
# ================================

cursor.execute("SELECT * FROM fault_info")
rows = cursor.fetchall()

for row in tqdm(rows, desc="导入 FaultInfo"):
    info_node = Node("FaultInfo",
                     fault_id=row["fault_id"],
                     category=row["fault_category"],
                     symptom=row["symptom"],
                     root_cause=row["root_cause"])
    graph.merge(info_node, "FaultInfo", "fault_id")

    # 建立关系 FaultInfo → FaultType
    type_node = graph.nodes.match("FaultType", type_id=row["type_id"]).first()
    if type_node:
        rel = Relationship(info_node, "HAS_TYPE", type_node)
        graph.merge(rel)

print(f"✅ FaultInfo 导入完成，共 {len(rows)} 条记录。\n")

# ================================
# 5️⃣ 导入 FaultSolution 节点 + 关系
# ================================

cursor.execute("SELECT * FROM fault_solution")
rows = cursor.fetchall()

for row in tqdm(rows, desc="导入 FaultSolution"):
    sol_node = Node("FaultSolution",
                    solution_id=row["solution_id"],
                    solution=row["solution"])
    graph.merge(sol_node, "FaultSolution", "solution_id")

    # 建立关系 FaultInfo → FaultSolution
    info_node = graph.nodes.match("FaultInfo", fault_id=row["fault_id"]).first()
    if info_node:
        rel = Relationship(info_node, "HAS_SOLUTION", sol_node)
        graph.merge(rel)

print(f"✅ FaultSolution 导入完成，共 {len(rows)} 条记录。\n")

# ================================
# 6️⃣ 清理并结束
# ================================

cursor.close()
mysql_conn.close()

print("🎯 所有数据已成功导入 Neo4j！")
print("💡 现在可以在 Neo4j Browser 中运行：\n")
print("""
MATCH (t:FaultType)<-[:HAS_TYPE]-(f:FaultInfo)-[:HAS_SOLUTION]->(s:FaultSolution)
RETURN t.name AS 类型, f.category AS 故障类别, s.solution AS 解决方案
LIMIT 20;
""")


